import os
import re
import json
from PIL import Image
import common

IMAGE_JSON = {
    "images": [
        {
            "idiom": "universal",
            "scale": "1x"
        },
        {
            "filename": "tmp@2x.png",
            "idiom": "universal",
            "scale": "2x"
        },
        {
            "filename": "tmp@3x.png",
            "idiom": "universal",
            "scale": "3x"
        }
    ],
    "info": {
        "author": "xcode",
        "version": 1
    }
}


class ImagesReplacement(object):
    sourceImagesPath = ""
    targetImagesPath = ""
    launchImage = ""
    _cur_name = ""

    @property
    def _cur_image_fold(self):
        return self._cur_name + ".imageset"

    def __init__(self, sourceImagesPath, targetImagesPath, launchImage):
        self.sourceImagesPath = sourceImagesPath
        self.targetImagesPath = targetImagesPath
        self.launchImage = launchImage

    def replace_images_resources(self):

        print("开始图片资源替换")
        if not os.path.exists(self.sourceImagesPath):
            print("没有找到图片配置文件")
            return
        if not os.path.exists(self.targetImagesPath):
            print("没有找到工程图片文件夹")
            return

        files = os.listdir(self.sourceImagesPath)
        newFolds = []
        for filename in files:
            ext = os.path.splitext(filename)
            if filename == self.launchImage:
                continue
            if ext[1] == ".png":
                self._cur_name = ext[0]
                common.remake_dir(self._cur_image_fold)
                self._create_file()
                newFolds.append(self._cur_image_fold)

        for dirPath, dirNames, filenames in os.walk(self.targetImagesPath):
            for dirName in dirNames:
                if newFolds.count(dirName) > 0:
                    path = os.path.join(dirPath, dirName)
                    common.move_dir(dirName, path)

        for fold in newFolds:
            common.remove_dir(fold)

    def _create_file(self):
        tmpDict = IMAGE_JSON
        for image in tmpDict["images"]:
            if image.get("filename") is not None:
                scale = image["scale"]
                int_scale = int(re.split("x", scale)[0])

                filaName = self._cur_name + "@" + scale + ".png"
                image["filename"] = filaName
                self._create_image(filaName, int_scale)

        file = open((self._cur_image_fold + "/Contents.json"), 'w')
        tmpStr = json.dumps(tmpDict, sort_keys=False, indent=4, separators=(',', ': '))
        file.write(tmpStr)
        file.close()

    def _create_image(self, filaName, scale):
        oImage = Image.open(self.sourceImagesPath + "/" + self._cur_name + ".png")

        w = int(oImage.size[0] * scale / 3)
        h = int(oImage.size[1] * scale / 3)
        if w == 0:
            w = 1
        if h == 0:
            h = 1
        s = w, h
        newImage = oImage.convert('RGBA').resize(s)
        newImage.save(self._cur_image_fold + "/" + filaName)


if __name__ == '__main__':

    imager = ImagesReplacement("/Users/yinqiong/Desktop/slice_0308", "/Users/yinqiong/Desktop/Assets.xcassets", "")
    imager.replace_images_resources()
